package com.crrc.sandameter.view

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import com.cj.mvvmlib.base.activity.BaseVmActivity
import com.cj.mvvmlib.base.viewmodel.BaseViewModel
import com.cj.mvvmlib.util.ToastUtil
import com.crrc.sandameter.Constant
import com.crrc.sandameter.DeviceManager
import com.crrc.sandameter.DialogUtils
import com.crrc.sandameter.InitDeviceCallback
import com.crrc.sandameter.R
import com.crrc.sandameter.common.LogFileUtils
import com.crrc.sandameter.common.SPUtil
import com.crrc.sandameter.databinding.ActivityLoginBinding
import com.crrc.sandameter.device.REGISTER_ADD
import com.crrc.sandameter.entity.UserInfo
import com.crrc.sandameter.http.API
import com.crrc.sandameter.http.GET
import com.crrc.sandameter.http.RequestBean
import com.crrc.sandameter.http.http
import com.crrc.sandameter.http.parseObject
import pub.devrel.easypermissions.EasyPermissions

class LoginActivity : BaseVmActivity<BaseViewModel>() {
    private val TAG = "LoginActivity"
    private lateinit var loginBinding: ActivityLoginBinding

    override fun useTitleBar(): Boolean {
        return false
    }

    override fun layoutId(): View {
        loginBinding = ActivityLoginBinding.inflate(layoutInflater)
        return loginBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        val version = DeviceManager.getDeviceVersion()
        loginBinding.versionTv.text = "版本: $version"
    }

    override fun initData() {
        val permissions = arrayOf(Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE)
        if (EasyPermissions.hasPermissions(this, *permissions)) {

        } else {
            requestPermissions(permissions, 101)
        }
        DeviceManager.deviceInit(DeviceManager.COM_NAME, 19200, object : InitDeviceCallback {
            override fun initFailed() {
                ToastUtil.showShortToast("设备连接失败")
            }

            override fun initSuccess() {
                DeviceManager.getDeviceVersion()
            }
        }) //与设备建立连接
    }

    override fun setListener() {
        loginBinding.calibrationBt.setOnClickListener {
            val dialog = DialogUtils.showDiyDialog(this,
                R.layout.layout_in_factory_dialog,
                width = ViewGroup.LayoutParams.WRAP_CONTENT,
                height = ViewGroup.LayoutParams.WRAP_CONTENT)
            val cancel_bt = dialog.findViewById<Button>(R.id.cancel_bt)
            cancel_bt.setOnClickListener {
                dialog.dismiss()
            }
            val confirm_bt = dialog.findViewById<Button>(R.id.confirm_bt)
            val password_et = dialog.findViewById<EditText>(R.id.password_et)
            confirm_bt.setOnClickListener {
                val code = password_et.text.toString()
                if (code == "654321") {
                    dialog.dismiss()
                    startActivity(Intent(/* packageContext = */ this, /* cls = */
                        CalibrationActivity::class.java))
                } else {
                    ToastUtil.showShortToast("密码错误")
                }
            }
        }
        loginBinding.loginBt.setOnClickListener {
            login()
        }
    }

    override fun createObserver() {
        DeviceManager.deviceData.observe(this) {
            val functionCode = it.substring(0, 4)
            if (functionCode == REGISTER_ADD.DEVICE_VERSION) {
                ToastUtil.showShortToast("设备连接成功")
            }
        }
    }

    private fun timeSync(authNo: String) {
        http {
            url = API.getBaseUrl() + API.CALIBRATION_TIME
            requestType = GET
            paramters["authNo"] = authNo
            paramters["timeMillis"] = System.currentTimeMillis().toString()
            success = {
                LogFileUtils.writeTxtToFile("时间校验返回数据：$it")
                personSync()
            }
            fail = { code, message -> }
        }
    }

    private fun personSync() {
        http {
            url = API.getBaseUrl() + API.PERSON_SYNC
            requestType = GET
            paramters["authNo"] = SPUtil.get(Constant.authNo, "").toString()
            success = {
                LogFileUtils.writeTxtToFile("人员同步返回数据：$it")
            }
            fail = { code, message -> }
        }
    }

    private fun login() {
        val userName = loginBinding.usernameEt.text.toString()
        val password = loginBinding.passwordEt.text.toString()
        if (userName.isEmpty() || password.isEmpty()) {
            ToastUtil.showShortToast("用户名或密码不能为空")
            return
        }
        http {
            url = API.getBaseUrl() + API.LOGIN
            requestType = GET
            paramters["authNo"] = SPUtil.get(Constant.authNo, "").toString()
            paramters["userName"] = userName
            paramters["password"] = password
            success = {
                val user = parseObject<RequestBean<UserInfo>>(it).data
                SPUtil.put(Constant.userName, user?.personName ?: "")
                SPUtil.put(Constant.account, userName)
                LogFileUtils.writeTxtToFile("登录返回数据：$it")
                startActivity(Intent(this@LoginActivity, DataCollectionActivity::class.java))
            }
            fail = { code, message ->
                ToastUtil.showShortToast(message)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onResume() {
        super.onResume()
        LogFileUtils.writeTxtToFile("进入登录页面")
        val authNo = SPUtil.get(Constant.authNo, "").toString()
        if (authNo.isEmpty()) {
            startActivity(Intent(this, RegisterDeviceActivity::class.java))
        } else {
            timeSync(authNo)
        }
    }

    private fun formatDeviceId(deviceId: String?): String? {
        if (deviceId == null || deviceId.length < 12) {
            return null
        }

        val builder = StringBuilder() // 截取前12个字符
        val truncatedId = deviceId.substring(0, 12)

        for (i in truncatedId.indices) {
            builder.append(truncatedId[i])
            if (i % 2 == 1 && i < 11) { // 每隔两个字符添加一个下划线
                builder.append("-")
            }
        }
        return builder.toString().uppercase() // 转换为大写
    }

    inner class AuthNo(val authNo: String)
}